import React, { useEffect, useState, useRef, useId } from "react";
import { Layout, List, Avatar, Button, Input, Spin, Typography } from "antd";
import { MessageOutlined, LoadingOutlined } from "@ant-design/icons";
import service from "@/http/request";
import { useParams } from "react-router-dom";

const { Sider, Content } = Layout;
const { Text } = Typography;

const PAGE_SIZE = 200;

const MessageListView = () => {
  const [conversations, setConversations] = useState([]);
  const [pageNum, setPageNum] = useState(1);
  const [selectedUserId, setSelectedUserId] = useState(null);
  const [messages, setMessages] = useState([]);
  const [messagePageNum, setMessagePageNum] = useState(1);
  const [inputContent, setInputContent] = useState("");
  const [loadingConversations, setLoadingConversations] = useState(false);
  const [loadingMessages, setLoadingMessages] = useState(false);
  const messagesEndRef = useRef(null);

  const { userId } = useParams(); // 获取路由参数
  console.log(userId);

  useEffect(() => {
    if (!userId) return;

    const userIdNum = Number(userId);

    const existing = conversations.find(
      (item) => item.otherUserId === userIdNum
    );
    if (existing) {
      setSelectedUserId(userIdNum);
    } else {
      // 如果该用户不在已有会话中，调用初始化接口
      service
        .post("/messages/init", { receiverId: userIdNum })
        .then(() => {
          // 再次拉取会话列表并选中该用户
          return service.get("/messages/conversations", {
            params: { pageNum: 1, pageSize: PAGE_SIZE },
          });
        })
        .then((res) => {
          const newList = res.records || [];
          setConversations(newList);
          setPageNum(1);
          setSelectedUserId(userIdNum);
        })
        .catch((err) => {
          console.error("初始化会话失败", err);
        });
    }
  }, [userId, conversations]);

  useEffect(() => {
    if (!selectedUserId) return;

    const interval = setInterval(() => {
      service
        .get(`/messages/conversation/${selectedUserId}`, {
          params: { pageNum: 1, pageSize: PAGE_SIZE },
        })
        .then((res) => {
          const newMessages = res.records || [];

          // 根据已有消息，判断是否需要更新（可根据时间戳或id）
          if (newMessages.length > 0 && messages.length > 0) {
            const latestNewMsgId = newMessages[newMessages.length - 1].id;
            const latestOldMsgId = messages[messages.length - 1].id;
            if (latestNewMsgId !== latestOldMsgId) {
              setMessages(newMessages);
            }
          } else if (newMessages.length > 0 && messages.length === 0) {
            setMessages(newMessages);
          }
        })
        .catch((err) => {
          console.error("轮询获取新消息失败", err);
        });
    }, 3000); // 每3秒轮询一次

    return () => clearInterval(interval); // 清除定时器
  }, [selectedUserId, messages]);

  // 拉取会话列表
  useEffect(() => {
    setLoadingConversations(true);
    service
      .get("/messages/conversations", {
        params: { pageNum, pageSize: PAGE_SIZE },
      })
      .then((res) => {
        if (pageNum === 1) {
          setConversations(res.records || []);
        } else {
          setConversations((prev) => [...prev, ...(res.records || [])]);
        }
      })
      .catch((err) => {
        console.error("获取会话列表失败", err);
      })
      .finally(() => setLoadingConversations(false));
  }, [pageNum]);

  // 拉取聊天记录
  useEffect(() => {
    if (!selectedUserId) return;
    setLoadingMessages(true);
    service
      .get(`/messages/conversation/${selectedUserId}`, {
        params: { pageNum: messagePageNum, pageSize: PAGE_SIZE },
      })
      .then((res) => {
        if (messagePageNum === 1) {
          setMessages(res?.records || []);
        } else {
          setMessages((prev) => [...(res?.records || []), ...prev]);
        }
      })
      .catch((err) => {
        console.error("获取聊天记录失败", err);
      })
      .finally(() => setLoadingMessages(false));
  }, [selectedUserId, messagePageNum]);

  // 发送消息
  const sendMessage = () => {
    if (!selectedUserId || !inputContent.trim()) return;

    service
      .post("/messages", {
        receiverId: selectedUserId,
        content: inputContent.trim(),
      })
      .then(() => {
        setInputContent("");
        // 重新请求第一页消息，刷新聊天记录
        setMessagePageNum(1);
        // 这里主动拉取最新消息
        service
          .get(`/messages/conversation/${selectedUserId}`, {
            params: { pageNum: 1, pageSize: PAGE_SIZE },
          })
          .then((res) => {
            setMessages(res.records || []);
          })
          .catch((err) => {
            console.error("刷新消息失败", err);
          });
      })
      .catch((err) => {
        console.error("发送消息失败", err);
      });
  };

  // 自动滚动到底部
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages]);

  // 切换聊天时重置分页
  useEffect(() => {
    setMessagePageNum(1);
    setMessages([]);
  }, [selectedUserId]);

  return (
    <Layout style={{ height: "90vh", background: "#fff" }}>
      {/* 会话列表侧边栏 */}
      <Sider
        width={320}
        style={{
          background: "#fafafa",
          borderRight: "1px solid #ddd",
          overflowY: "auto",
        }}
      >
        <div
          style={{
            padding: 16,
            fontWeight: "bold",
            fontSize: 20,
            borderBottom: "1px solid #ddd",
          }}
        >
          会话列表
        </div>

        {loadingConversations && pageNum === 1 ? (
          <div style={{ textAlign: "center", padding: 20 }}>
            <Spin
              indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
            />
          </div>
        ) : conversations.length === 0 ? (
          <div style={{ textAlign: "center", padding: 20, color: "#999" }}>
            暂无会话
          </div>
        ) : (
          <List
            itemLayout="horizontal"
            dataSource={conversations}
            renderItem={(item) => (
              <List.Item
                style={{
                  backgroundColor:
                    selectedUserId === item.otherUserId
                      ? "#e6f7ff"
                      : "transparent",
                  cursor: "pointer",
                  padding: "12px 16px",
                  borderBottom: "1px solid #eee",
                }}
                onClick={() => setSelectedUserId(item.otherUserId)}
              >
                <List.Item.Meta
                  avatar={<Avatar>{item.otherUsername?.[0]}</Avatar>}
                  title={<Text strong>{item.otherUsername}</Text>}
                  description={
                    <Text type="secondary" ellipsis>
                      {item.lastMessageContent || "暂无消息"}
                    </Text>
                  }
                />
              </List.Item>
            )}
          />
        )}

        {conversations.length >= PAGE_SIZE && !loadingConversations && (
          <div style={{ padding: 16, textAlign: "center" }}>
            <Button
              type="primary"
              block
              onClick={() => setPageNum((prev) => prev + 1)}
            >
              加载更多
            </Button>
          </div>
        )}
      </Sider>

      {/* 聊天内容区 */}
      <Layout>
        <Content style={{ display: "flex", flexDirection: "column" }}>
          {/* 标题 */}
          <div
            style={{
              padding: "16px",
              borderBottom: "1px solid #ddd",
              fontWeight: "bold",
              fontSize: 18,
            }}
          >
            {selectedUserId
              ? conversations.find((c) => c.otherUserId === selectedUserId)
                  ?.otherUsername || "聊天"
              : "请选择会话"}
          </div>

          {/* 消息列表 */}
          <div
            style={{
              flex: 1,
              overflowY: "auto",
              padding: 16,
              backgroundColor: "#f5f5f5",
            }}
          >
            {selectedUserId ? (
              <>
                {loadingMessages && messagePageNum === 1 && (
                  <div
                    style={{
                      textAlign: "center",
                      margin: "10px 0",
                      color: "#999",
                    }}
                  >
                    <Spin size="small" /> 加载中...
                  </div>
                )}
                {messagePageNum > 1 && (
                  <div style={{ textAlign: "center", marginBottom: 12 }}>
                    <Button
                      size="small"
                      onClick={() => setMessagePageNum((prev) => prev + 1)}
                    >
                      加载更多历史消息
                    </Button>
                  </div>
                )}
                {messages.length === 0 && !loadingMessages && (
                  <div
                    style={{
                      textAlign: "center",
                      color: "#999",
                      marginTop: 20,
                    }}
                  >
                    暂无消息
                  </div>
                )}
                {messages.map((msg) => {
                  const isMe = msg.senderId !== selectedUserId;
                  return (
                    <div
                      key={msg.id}
                      style={{
                        display: "flex",
                        flexDirection: "column",
                        alignItems: isMe ? "flex-end" : "flex-start",
                        marginBottom: 12,
                      }}
                    >
                      <div
                        style={{
                          backgroundColor: isMe ? "#1890ff" : "#e5e5ea",
                          color: isMe ? "#fff" : "#000",
                          padding: "8px 12px",
                          borderRadius: 16,
                          maxWidth: "70%",
                          wordBreak: "break-word",
                        }}
                      >
                        {msg.content}
                      </div>
                      <div
                        style={{ fontSize: 12, color: "#999", marginTop: 4 }}
                      >
                        {new Date(msg.createdAt).toLocaleString()}
                      </div>
                    </div>
                  );
                })}
                <div ref={messagesEndRef} />
              </>
            ) : (
              <div
                style={{ textAlign: "center", color: "#999", marginTop: 50 }}
              >
                请选择左侧会话开始聊天
              </div>
            )}
          </div>

          {/* 输入框 */}
          <div
            style={{
              padding: "12px 16px",
              borderTop: "1px solid #ddd",
              display: "flex",
              alignItems: "center",
              background: "#fff",
            }}
          >
            <Input.TextArea
              value={inputContent}
              onChange={(e) => setInputContent(e.target.value)}
              placeholder="输入消息"
              autoSize={{ minRows: 1, maxRows: 4 }}
              onPressEnter={(e) => {
                if (!e.shiftKey) {
                  e.preventDefault();
                  sendMessage();
                }
              }}
              disabled={!selectedUserId}
              style={{ flex: 1, resize: "none" }}
            />
            <Button
              type="primary"
              onClick={sendMessage}
              disabled={!selectedUserId || !inputContent.trim()}
              style={{ marginLeft: 12, fontWeight: "bold" }}
            >
              发送
            </Button>
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default MessageListView;
